#!/usr/bin/env python2.5

import datetime, hmac, sha, base64, urllib, simplejson, sys

def _generateTimestamp():
    return "2008-06-28T17:26:08+00:00"
    #return datetime.datetime.utcnow().isoformat()[0:19]+"+00:00"

def _generateSignature(secret, params):
    signature = ""
    for key in sorted(params.keys(), key=str.lower):
        signature = signature + key + str(params[key])
    print "Signature over: %s" % signature
    return base64.encodestring(hmac.new(secret, signature, sha).digest()).strip()

def _generateRequestUrl(endpoint, version, action, accessKey, secretKey, params):
    parameters = {}
    for key,value in params.iteritems():
        if type(value) in (list, tuple):
            for n,v in enumerate(value):
                parameters["%s.%d" % (key, n)] = v
        else:
            parameters[key] = str(value)
    parameters['Action'] = action
    parameters['Version'] = version
    if accessKey:
        parameters['AccessKey'] = accessKey
        parameters['SignatureVersion'] = "1"
        parameters['Timestamp'] = _generateTimestamp()
        parameters['Signature'] = _generateSignature(secretKey, parameters)
    return "%s?%s" % (endpoint, urllib.urlencode(parameters))

def executeCall(endpoint, version, action, accessKey = None, secretKey = None, parameters = {}):
    url = _generateRequestUrl(endpoint, version, action, accessKey, secretKey, parameters)
    print url
    response = urllib.urlopen(url).read()
    return simplejson.loads(response)

#

response = executeCall('http://localhost:8080/SignService', '2009-02-03', 'ShowMessage',
    parameters = { 'Border': 'Thin', 'Message': sys.argv[1], 'FontName': sys.argv[2], 'FontSize': int(sys.argv[3]) })

print response

